package com.atguigu.ftp.service.impl;

import com.atguigu.ftp.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author panghl
 * @Date 2021/1/6 10:33
 * @Description TODO
 **/
@Service
public class FileServiceImpl implements FileService {

    @Value("${edu.file.path}")
    private String fileRootPath;

    @Override
    public List<String> uploadFiles(MultipartFile[] files) {
        List<String> urls = new ArrayList<>();
        int index = 0;
        String filePath = "";
        for (MultipartFile file : files) {
            index += 1;
            // 上传简单文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            if (originalFilename.lastIndexOf(".") >= 0) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            // 存储路径
            filePath = new StringBuilder(fileRootPath).append(System.currentTimeMillis() + "-" + index + "-" + UUID.randomUUID()).append(suffix).toString();
            try {
                // 保存文件
                file.transferTo(new File(filePath));
                urls.add(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return urls;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        String filePath = "";
        int index = 0;
        // 上传简单文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = "";
        if (originalFilename.lastIndexOf(".") >= 0) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        // 存储路径
        filePath = new StringBuilder(fileRootPath).append(System.currentTimeMillis() + "-" + index + "-" + UUID.randomUUID()).append(suffix).toString();
        try {
            // 保存文件
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
}
